package com.itheima.consul.controller;


import com.itheima.consul.domain.Goods;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;

/**
 * 服务的调用方
 */

@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private DiscoveryClient discoveryClient;

    @GetMapping("/goods/{id}")
    public Goods findGoodsById(@PathVariable("id") int id) {
        System.out.println("findGoodsById..." + id);


        /*//手动将消费端的url地址封装成url
        String url = "http://localhost:8001/goods/findOne/1" + id;
        //消费端直接通过RestTemplate实现远程调用
        Goods good = restTemplate.getForObject(url, Goods.class);*/

        //discoveryClient 使用的参数就是配置文件中设置的应用名称或者是eureka中的实例对象的名称
        List<ServiceInstance> instances = discoveryClient.getInstances("consul-provider");
        //短路效果,如果此处成立,则不再执行下面的代码
        if (instances == null || instances.size() == 0) {
            return null;
        }

        ServiceInstance instance = instances.get(0);
        String host = instance.getHost();
        int port = instance.getPort();
        System.out.println(host);
        System.out.println(port);

        //手动将消费端的url地址封装成url
        String url = "http://" + host + ":" + port + "/goods/findOne/1" + id;
        //消费端直接通过RestTemplate实现远程调用
        Goods good = restTemplate.getForObject(url, Goods.class);
        //远程调用Goods服务中的findOne接口*/
        return good;
    }
}
